$(document).ready(function () {
  var table = $('table#table').DataTable({
      initComplete: function(settings, json) {
          $("#table").removeClass('dataTable');
          $("#table").parent().addClass('table-responsive');

          $("#table").parent()
              .css('max-height', $(window).height() - $('#query-area').height() - 260)
              .css('height', 'auto')
              .css('overflow-y', 'visible');

          $("#table").on('change', 'input[type="checkbox"]', function () {
              if($(this).prop('checked')) {
                  $(this).closest('tr').addClass('warning');
              } else {
                  $(this).closest('tr').removeClass('warning');
              }
          });

          // 动态添加搜索条件行间距样式
        $('<style>').text(`#query-area .form-group {margin-bottom: 15px;}`).appendTo('head');

        // 动态添加表头居中样式
        $('<style>').text('#table thead th { text-align: center !important; }').appendTo('head');

        // 添加行点击事件处理
          $("#table tbody").on('click', 'tr', function(e) {
              // 避免点击复选框本身时触发两次
              if (!$(e.target).is('input[type="checkbox"]')) {
                  // 找到当前行的复选框
                  var checkbox = $(this).find('input[type="checkbox"]').first();
                  // 切换复选框状态
                  checkbox.prop('checked', !checkbox.prop('checked'));
                  // 触发change事件以更新行样式
                  checkbox.trigger('change');
              }
          });
      },
    ajax: {
      url: baseUrl + '/datatable',
      data : function(d) {
		var no             = $('.search-form').find('input[name="documentNumber"]').val();
        var type           = $('.search-form').find('select#type').val();
        var status         = $('.search-form').find('select#status').val();
        var material       = $('.search-form').find('select#material').val();
        var materialcode   = $('.search-form').find('input[name="materialcode"]').val();
        var materialname   = $('.search-form').find('input[name="materialname"]').val();
        var connum         = $('.search-form').find('input[name="containnum"]').val();
        var lotattr07      = $('.search-form').find('input[name="lotattr07"]').val();
        var fromdate       = $('.search-form').find('input[name="fromdate"]').val();
        var todate         = $('.search-form').find('input[name="todate"]').val();
        d.no       = no;
        d.type     = type;
        d.status   = status;
        d.material = material;
        d.materialcode = materialcode;
        d.materialname = materialname;
        d.containnum   = connum;
        d.lotattr07    = lotattr07;
        d.fromdate     = fromdate;
        d.todate       = todate;
		return d;
      }
    },
    order: [
      [1, 'asc']
    ],
    columns: [{
      data: 'id',
      sortable: false,
      defaultContent: '',
      'class': 'text-center',
      render: function (data, type, row, meta) {
          return '<input type="checkbox" name="ids" value="' + data + '" style="transform: scale(1.5);"/>'
      }

     },{
      name: 'documentNumber',
      data: 'documentNumber',
      'class': 'text-center',
    },{
      name: 'expectedTime',
      data: 'expectedTime',
     'class': 'text-center',
    },{
      name: 'planLoadPlace',
      data: 'planLoadPlace',
     'class': 'text-center',
      render: function (data, type, row, meta) {
            if (data=="")        return "";
            if (data==null)      return "";
            if (data==undefined) return "";
            return data.replace('2023', '东1')
                       .replace('2028', '东2')
                       .replace('2033', '东3')
                       .replace('2038', '东4')
                       .replace('1023', '西1')
                       .replace('1028', '西2')
                       .replace('1033', '西3')
                       .replace('1038', '西4')
                ;
        }
    },{
      data: "id",
      defaultContent: '',
      sortable: false,
      'class': 'text-center',
      render: function (data, type, row, meta) {
         //return '<a class="btn btn-default btn-xs" href="'+rootUrl+'/inventory/codetails/'+ row.id + '"><i class="fa fa-list"></i></a>';
          return `<button type="button" class="btn btn-default btn-xs" onclick="showCodetail(${row.id})"><i class="fa fa-list"></i></button>`;
      }
    },{
        name: 'createSource',
        data: 'createSource',
        'class': 'text-center',
    },{
        name: 'createdDate',
        data: 'createdDate',
        'class': 'text-center',
    },{
      name: 'status',
      data: 'status',
      'class': 'text-center',
      render: function (data, type, row, meta) {
      	return VALUES_MAP_DICT_STATUS && VALUES_MAP_DICT_STATUS[data] ? VALUES_MAP_DICT_STATUS[data].text : '';
      }
    },
    //     {
    //   data: "enabled",
    //   defaultContent: '',
    //   sortable: false,
    //   'class': 'text-center',
    //   render: function (data, type, row, meta) {
    //     var result = '<a class="btn btn-xs btn-default enable" href="javascript:;">';
    //     if (data) {
    //       result += '<i title="激活/禁用" class="fa fa-check-square-o"/>';
    //     } else {
    //       result += '<i title="激活/禁用" class="fa fa-square-o"/>';
    //     }
    //     result += '</a>';
    //     return result;
    //   }
    // },
        {
      data: "id",
      defaultContent: '',
      sortable: false,
      'class': 'text-center',
      render: function (data, type, row, meta) {
        return ('<div class="btn-group">' +
          '<a class="btn btn-default btn-xs del" title="删除" href="#"><i class="fa fa-trash-o"></i></a>' +
          '</div>' +
          '&nbsp;&nbsp;');
      }
    }]
  });

  table.on('click', '.del', function () {
    var id = table.row($(this).parents('tr')).data().id;
    $("#delForm #ids").val(id);
    if (id) {
      bootbox.confirm("确定要删除数据吗?", function (result) {
        if (result) {
          $("#delForm").submit();
        }
      });
    }
  });


    $(".btn.genDetailsAll").on("click", function (e) {
        var ids = [];
        $('#table>tbody input:checked').each(function (i, item) {
            ids.push($(item).val());
        });
        $("#genDetailsForm #ids").val(ids.join(","));
        if (ids.length > 0) {
            bootbox.confirm("确定要生成明细的数据吗?", function (result) {
                if (result) {
                    $("#genDetailsForm").submit();
                }
            });
        } else {
            bootbox.alert("请选择要生成明细的数据.");
        }
    });

    //
    $(".btn.workstationAll").on("click", function (e) {
        var ids = [];
        $('#table>tbody input:checked').each(function (i, item) {
            ids.push($(item).val());
        });
        $("#workstationForm #ids").val(ids.join(","));
        if (ids.length > 0) {
            $('#workStationModal').modal('show')
        } else {
            bootbox.alert("请选择设定盘点站台的数据.");
        }
    });

    $("#workstations-d-allbox").on('change', function(e){
        if (this.checked) {
            document.getElementById("workstation-d1").checked = true;
            document.getElementById("workstation-d2").checked = true;
            document.getElementById("workstation-d3").checked = true;
            document.getElementById("workstation-d4").checked = true;
        } else {
            document.getElementById("workstation-d1").checked = false;
            document.getElementById("workstation-d2").checked = false;
            document.getElementById("workstation-d3").checked = false;
            document.getElementById("workstation-d4").checked = false;
        }
    });

    $("#workstations-x-allbox").on('change', function(e){
        if (this.checked) {
            document.getElementById("workstation-x1").checked = true;
            document.getElementById("workstation-x2").checked = true;
            document.getElementById("workstation-x3").checked = true;
            document.getElementById("workstation-x4").checked = true;
        } else {
            document.getElementById("workstation-x1").checked = false;
            document.getElementById("workstation-x2").checked = false;
            document.getElementById("workstation-x3").checked = false;
            document.getElementById("workstation-x4").checked = false;
        }
    });

    $("#workstation-btn").on("click", function (e) {
        if (isCheckboxed_(document.getElementsByName('workstations'))) {
            $("#workstationForm").submit();
        } else {
            bootbox.alert("请选择设定盘点站台.");
        }
    });

    $(".btn.genTaskAll").on("click", function (e) {
        var ids = [];
        $('#table>tbody input:checked').each(function (i, item) {
            ids.push($(item).val());
        });
        $("#genTaskForm #ids").val(ids.join(","));
        if (ids.length > 0) {
            bootbox.confirm("确定要生成盘点任务的数据吗?", function (result) {
                if (result) {
                    $("#genTaskForm").submit();
                }
            });
        } else {
            bootbox.alert("请选择要生成盘点任务的数据.");
        }
    });


    $(".btn.deliverAll").on("click", function (e) {
        var ids = [];
        $('#table>tbody input:checked').each(function (i, item) {
            ids.push($(item).val());
        });
        $("#deliverForm #ids").val(ids.join(","));
        if (ids.length > 0) {
            bootbox.confirm("确定要发布选中的数据吗?", function (result) {
                if (result) {
                    $("#deliverForm").submit();
                }
            });
        } else {
            bootbox.alert("请选择要发布的数据.");
        }
    });

  $(".btn.delAll").on("click", function (e) {
    var ids = [];
    $('#table>tbody input:checked').each(function (i, item) {
      ids.push($(item).val());
    });
    $("#delForm #ids").val(ids.join(","));
    if (ids.length > 0) {
      bootbox.confirm("确定要删除选中的数据吗?", function (result) {
        if (result) {
          $("#delForm").submit();
        }
      });
    } else {
      bootbox.alert("请选择要删除的数据.");
    }
  });

  $(".btn.alcAll").on("click", function (e) {
    var ids = [];
    $('#table>tbody input:checked').each(function (i, item) {
      ids.push($(item).val());
    });
    $("#alcForm #ids").val(ids.join(","));
    if (ids.length > 0) {
      bootbox.confirm("确定要分配选中的数据吗?", function (result) {
        if (result) {
          $("#alcForm").submit();
        }
      });
    } else {
      bootbox.alert("请选择要分配的数据.");
    }
  });

  $(".btn.printAll").on("click", function (e) {
      var ids = [];
      $('#table>tbody input:checked').each(function (i, item) {
          ids.push($(item).val());
      });
      $("#printForm #ids").val(ids.join(","));
      if (ids.length > 0) {
          bootbox.confirm("确定要打印的选定的数据吗?", function (result) {
              if (result) {
                  $("#printForm").submit();
              }
          });
      } else {
          bootbox.alert("请选择要打印的数据.");
      }
  });

  $(".btn.closeAll").on("click", function (e) {
    var ids = [];
    $('#table>tbody input:checked').each(function (i, item) {
      ids.push($(item).val());
    });
    $("#closeForm #ids").val(ids.join(","));
    if (ids.length > 0) {
      bootbox.confirm("确定要关闭的数据吗?", function (result) {
        if (result) {
          $("#closeForm").submit();
        }
      });
    } else {
      bootbox.alert("请选择要关闭的数据.");
    }
  });


  table.on('click', '.enable', function () {
    var that = this;
    var data = table.row($(this).parents('tr')).data();
    var id = data.id;
    var enabled = data.enabled;
    bootbox.confirm("确定要更新选中的数据吗?", function(resul) {
	if (resul) {
	    $.get(baseUrl + "/enable", {
	      enabled: !enabled,
	      ids: id
	    }, function (res) {
	      if (res) {
	        data.enabled = !enabled;
	        $(that).find("i").removeClass("fa-" + (enabled ? "check-" : "") + "square-o").addClass("fa-" + (!enabled ? "check-" : "") + "square-o");
	        toastr.info('操作成功!');
	      }

	    });
	}});
  });

    $('.form_datetime').datetimepicker({
        format: 'yyyy-mm-dd',
        weekStart: 1,
        autoclose: true,
        startView: 2,
        minView: 2,
        forceParse: false,
        language: 'cn',
        calendarWeeks: true,
        pickerPosition: "bottom-left"
    }).on('changeDate', function (ev) {
        daycount = 0;
        if (null != ev.date && undefined != ev.date) {
            var day = new Date(ev.date.getYear(), ev.date.getMonth(),ev.date.getDate());
            daycount = day.getDate();
        }

    });

    function isCheckboxed_(checkboxElements) {
        var len = checkboxElements.length;
        for (var i = 0; i < len; i++) {
            if (checkboxElements[i].checked) return true;
        }

        return false;
    }

    $('.search-form').on("submit", function (e) {
    table.draw();
    //阻止表单submit
    return false;
  });

});

function showCodetail(_id) {
    console.log(_id);
    var $modal = $("#coDetailModal");
    $modal.find("iframe").attr("src", `${rootUrl}/inventory/codetails/${_id}`);
    $modal.modal('show');
}
